//
//  LzwNewViewController.m
//  NewHalfsugar
//
//  Created by 刘志武 on 16/1/1.
//  Copyright © 2016年 刘志武. All rights reserved.
//

#import "LzwNewViewController.h"
#import "Block.h"
#import "AFNetworking.h"
#import "MJRefresh.h"
#import "LzwBaseView.h"
#import "LzwBaseImageView.h"
#import "UIImageView+WebCache.h"
#import "LzwNewBetweenCell.h"
#import "LzwNewTableTwoCell.h"
#import "LzwNewTwoController.h"
#import "LzwBetweenWebVIewVC.h"
#import "LzwFirstDetailVC.h"
#import "LzwTwoDetailVC.h"
#import "LzwThreeDetailVC.h"
#import "LzwFourDetailVC.h"
#import "LzwSingleton.h"
#import "SDImageCache.h"
#import "LzwBaseScrollView.h"
#import "LzwNewPageView.h"
#import "LzwFiveVebViewVC.h"


@interface LzwNewViewController ()<UITableViewDataSource, UITableViewDelegate, LzwNewBetweenCellDelegata, LzwNewPageViewDelegata>

@property (nonatomic, retain) UITableView *myNewTableView;


@property(nonatomic,retain)Reachability *conn;

@property (nonatomic, retain) LzwNewPageView *myNewView;


@end

@implementation LzwNewViewController

-(void)dealloc{
    [_myNewTableView release];
    [_myNewView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor orangeColor];

  
    self.myNewTableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStylePlain];
    self.myNewTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.myNewTableView];
    
  
    
    
    self.myNewTableView.delegate = self;
    self.myNewTableView.dataSource = self;
    
    
    [self.myNewTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.myNewTableView registerClass:[LzwNewBetweenCell class] forCellReuseIdentifier:@"cellC"];
    [self.myNewTableView registerClass:[LzwNewTableTwoCell class] forCellReuseIdentifier:@"cellTwo"];
    
    
    self.arrayHeader = [NSMutableArray array];
    self.arrayBetween = [NSMutableArray array];
    self.arrayFooter = [NSMutableArray array];
    
    

 
    //数据解析
    
    NSString *string = @"http://open3.bantangapp.com/recommend/index?app_installtime=1451365479.933367&app_versions=5.1.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&device_token=c02c60075e7bab110fbdf27e15de3cb61e97360c4ea3545fd8a5936e46c28ccb&os_versions=9.1&page=0&pagesize=20&screensize=640&track_device_info=iPhone5%2C3&track_deviceid=A80585E3-D6AD-4A53-BE1C-5963901C96E5&v=9";
    
    [Block creatingDataTask:string parameters:nil Cookie:nil User_Agent:nil successAFNBlock:^(id resuposeObject) {
        
        NSMutableDictionary *dic = [resuposeObject objectForKey:@"data"];
        
        
        NSMutableArray *array = [dic objectForKey:@"banner"];
        
        //轮播图数据
        for (NSMutableDictionary *dict in array) {
            
            LzwNewHeadModle *modleH = [[LzwNewHeadModle alloc]init];
            
            [modleH setValuesForKeysWithDictionary:dict];
            
            //插入数据库中
            [[LzwSingleton shareDataBase] deleteFirstTable:modleH.photo];
            [[LzwSingleton shareDataBase] insertLzwNewHeadIntoTable:modleH];
            
            [self.arrayHeader addObject:modleH];
            

            
        }
        self.myNewView.arrayNewView = self.arrayHeader;

    
        //中间的数据
        NSMutableArray *arrayThre = [dic objectForKey:@"entry_list"];
        
        for (NSMutableDictionary *dicTh in arrayThre) {
            
            LzwNewBetweenModle *modleBtw = [[LzwNewBetweenModle alloc]init];
            
            [modleBtw setValuesForKeysWithDictionary:dicTh];
            
            //插入数据库中
            [[LzwSingleton shareDataBase] deleteTwoTable:modleBtw.photo];
            [[LzwSingleton shareDataBase] insertLzwNewBetweenIntoTable:modleBtw];
            
            [self.arrayBetween addObject:modleBtw];
            
        }
        
        //最下面的cell
        
        NSMutableArray *ArrayTwo = [dic objectForKey:@"topic"];
        
    for (NSMutableDictionary *dicTwo in ArrayTwo) {
        
        LzwModleNewTwo *modleTwo = [[LzwModleNewTwo alloc]init];
        
    [modleTwo setValuesForKeysWithDictionary:dicTwo];
        
        //插入数据库中
        [[LzwSingleton shareDataBase] deleteThreeTable:modleTwo.title];
        [[LzwSingleton shareDataBase] insertLzwModleNewTwoIntoTable:modleTwo];
        
        [self.arrayFooter addObject:modleTwo];
                    
                    
}

        
        
    
}];

    
    
    self.myNewTableView.tableHeaderView = [self creatNewSubViews];
    
        NSMutableArray *array1 = [[LzwSingleton shareDataBase] selectNewHeaderTable];
    
        NSMutableArray *array2 = [[LzwSingleton shareDataBase] selectNewBetweenTable];
        NSMutableArray *array3 = [[LzwSingleton shareDataBase] selectNewFooterTable];
    
        self.myNewView.arrayNewView = [NSMutableArray arrayWithArray:array1];
    NSLog(@"array = %@", array2);
//        self.arrayBetween = [NSMutableArray arrayWithArray:array2];
        self.arrayFooter = [NSMutableArray arrayWithArray:array3];
    

    
    [self.myNewTableView reloadData];

    
    [_myNewTableView release];

    
    //刷新
    self.isUpLoading = NO;
    
    // 2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
    
    
}


- (LzwBaseView *)creatNewSubViews{

    
    self.myNewView = [[LzwNewPageView alloc]initWithFrame:CGRectMake(0, 0, 375 * WIDTH, 180 * WIDTH)];
    self.myNewView.myNewViewDelegata = self;
    [self.view addSubview:self.myNewView];
    
    
    return self.myNewView;
}



//collect协议方法
-(void)pushNewBetweenWebView:(NSString *)extent{
    
    LzwBetweenWebVIewVC *BetWebVc = [[LzwBetweenWebVIewVC alloc]init];
    
    BetWebVc.modleBetweenW.extend = extent;
    
    
    [self.navigationController pushViewController:BetWebVc animated:YES];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        return 1;
    }
 
    return self.arrayFooter.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
 if (indexPath.section == 0) {
     
     
     LzwNewBetweenCell *cellCollect = [tableView dequeueReusableCellWithIdentifier:@"cellC"];
     cellCollect.myLzwbetweenDelegata = self;
     
     cellCollect.selectionStyle = UITableViewCellSelectionStyleNone;
     
     cellCollect.arrayColl = self.arrayBetween;
     
     NSLog(@"....... = %ld", self.arrayBetween.count);
     
     return cellCollect;
     
 }else{
    

        LzwNewTableTwoCell *cellTw = [tableView dequeueReusableCellWithIdentifier:@"cellTwo"];
        
        cellTw.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cellTw.modleTwo = [self.arrayFooter objectAtIndex:indexPath.row];
        
        return cellTw;
    }
    
    
    
    return cell;
}



//点击cell触发事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {

        
        LzwNewTwoController *twoVC = [[LzwNewTwoController alloc]init];
        
        twoVC.modleN = [self.arrayFooter objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:twoVC animated:YES];

    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return 110;
    }

    return 260;
}




//刷新
#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block LzwNewViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myNewTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
//        [self.arrayHeader removeAllObjects];
        vc.nextPage = 0;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myNewTableView headerBeginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block LzwNewViewController *vc = self;
    
    // 添加上拉刷新尾部控件
    [self.myNewTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage ++;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
        
    }];
}

#pragma mark --使用AFN进行数据请求
-(void)GetPersonList:(NSInteger)nextCursor
{
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    

    
    NSString *url_string = [NSString stringWithFormat:@"http://open3.bantangapp.com/recommend/index?app_installtime=1451365479.933367&app_versions=5.1.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&device_token=c02c60075e7bab110fbdf27e15de3cb61e97360c4ea3545fd8a5936e46c28ccb&oauth_token=a41d3848f43102aa7759c27ba2c0fe8f&os_versions=9.1&page=%ld&pagesize=20&screensize=640",nextCursor];
    
    
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        NSMutableDictionary *dic = [responseObject objectForKey:@"data"];
        
        NSMutableArray *arrayAB = [dic objectForKey:@"topic"];
        
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.arrayFooter removeAllObjects];
        }
        
    
        
        for (NSMutableDictionary *dicAA  in arrayAB) {
        
            LzwModleNewTwo *modleTwo = [[LzwModleNewTwo alloc]init];

            [modleTwo setValuesForKeysWithDictionary:dicAA];

            [self.arrayFooter addObject:modleTwo];
            
        }
        
        
        [self.myNewTableView footerEndRefreshing];
        [self.myNewTableView headerEndRefreshing];
        [self.myNewTableView reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
    
    
}

//实现轮播图签订协议的方法
-(void)pushDetailPage:(NSInteger)xiaobiao{
    
    if (xiaobiao == 1) {
        LzwFirstDetailVC *firstVc = [[LzwFirstDetailVC alloc]init];
        
        [self.navigationController pushViewController:firstVc animated:YES];
        
    }else if (xiaobiao == 2){
        
        LzwFiveVebViewVC *fiveVC = [[LzwFiveVebViewVC alloc]init];
        
        fiveVC.url = @"http://7xlxny.com2.z0.glb.qiniucdn.com/pandian.html?v=1";
        
        [self.navigationController pushViewController:fiveVC animated:YES];
       
        
        
    }else if (xiaobiao == 3){
        
        LzwThreeDetailVC *threeVc = [[LzwThreeDetailVC alloc]init];
        
        [self.navigationController pushViewController:threeVc animated:YES];

        
    }else if (xiaobiao == 4){
       
        LzwFourDetailVC *fourVc = [[LzwFourDetailVC alloc]init];
        
        
        [self.navigationController pushViewController:fourVc animated:YES];
        
        
    }else{
        LzwTwoDetailVC *twoVc = [[LzwTwoDetailVC alloc]init];
        
        [self.navigationController pushViewController:twoVc animated:YES];

    }
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
